<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天助手 - 真实通义千问</title>
    <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='75' font-size='75' fill='%23667eea'>🤖</text></svg>">
    <!-- markdown-it库 -->
    <script src="https://cdn.jsdelivr.net/npm/markdown-it/dist/markdown-it.min.js"></script>
    <!-- highlight.js -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 20px;
            padding: 20px;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
        }

        .header p {
            font-size: 1em;
            opacity: 0.9;
        }

        .badge {
            display: inline-block;
            background: #4CAF50;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.9em;
            margin-left: 10px;
        }

        .chat-container {
            flex: 1;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            display: flex;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 8px;
            word-wrap: break-word;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 0 12px 12px;
        }

        .message.assistant .message-content {
            background: #f0f0f0;
            color: #333;
            border-radius: 0 12px 12px 12px;
        }

        /* Markdown样式 */
        .content {
            line-height: 1.8;
            color: #333;
        }

        .content h1, .content h2, .content h3, .content h4, .content h5, .content h6 {
            margin-top: 15px;
            margin-bottom: 10px;
            color: #667eea;
        }

        .content p {
            margin: 10px 0;
        }

        .content code {
            background: #f5f5f5;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            color: #d32f2f;
        }

        .content pre {
            background: #0a1929;
            color: #64ffda;
            padding: 12px;
            border-radius: 6px;
            overflow-x: auto;
            margin: 10px 0;
            border-left: 4px solid #667eea;
        }

        .content pre code {
            background: none;
            color: inherit;
            padding: 0;
        }

        .content a {
            color: #667eea;
            text-decoration: none;
        }

        .content a:hover {
            text-decoration: underline;
        }

        .content ul, .content ol {
            margin: 10px 0 10px 30px;
        }

        .content li {
            margin: 5px 0;
        }

        .content blockquote {
            border-left: 4px solid #667eea;
            padding-left: 12px;
            margin: 10px 0;
            color: #666;
            font-style: italic;
        }

        .content img {
            max-width: 100%;
            max-height: 300px;
            border-radius: 6px;
            margin: 10px 0;
        }

        .input-area {
            padding: 20px;
            background: #f8f9fa;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
        }

        .input-group {
            flex: 1;
            display: flex;
            gap: 10px;
        }

        input[type="text"] {
            flex: 1;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 1em;
            transition: all 0.3s ease;
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        button {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-send {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-send:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }

        .btn-send:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-clear {
            background: #f0f0f0;
            color: #333;
        }

        .btn-clear:hover {
            background: #e0e0e0;
        }

        .status {
            padding: 10px 15px;
            background: #e8f5e9;
            color: #388e3c;
            border-radius: 6px;
            font-size: 0.9em;
            text-align: center;
            display: none;
        }

        .status.show {
            display: block;
        }

        .status.error {
            background: #ffebee;
            color: #c62828;
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 1.8em;
            }

            .message-content {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 AI聊天助手<span class="badge">真实API</span></h1>
            <p>基于阿里巴巴通义千问 + SSE流式传输（真实集成）</p>
        </div>

        <div class="chat-container">
            <div class="messages" id="messages"></div>

            <div class="input-area">
                <div class="input-group">
                    <input type="text" id="userInput" placeholder="输入你的问题... 按Enter发送" autocomplete="off">
                    <button class="btn-send" id="sendBtn" onclick="sendMessage()">发送</button>
                    <button class="btn-clear" onclick="clearMessages()">清空</button>
                </div>
            </div>
        </div>

        <div class="status" id="status"></div>
    </div>

    <script>
        // 初始化markdown-it
        const md = window.markdownit({
            html: false,
            linkify: true,
            typographer: true,
            highlight: function (str, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(str, { language: lang }).value;
                }
                return '';
            }
        });

        function sendMessage() {
            const userInput = document.getElementById('userInput');
            const question = userInput.value.trim();

            if (!question) {
                showStatus('请输入问题', true);
                return;
            }

            // 禁用输入和按钮
            userInput.disabled = true;
            document.getElementById('sendBtn').disabled = true;

            // 显示用户消息
            addMessage(question, 'user');

            // 清空输入框
            userInput.value = '';

            // 发送请求到后端（使用真实API）
            const eventSource = new EventSource(`/test/ai/qwen-stream?question=${encodeURIComponent(question)}`);
            
            let assistantMessageDiv = null;
            let contentDiv = null;
            let fullContent = '';

            // 监听消息事件
            eventSource.addEventListener('message', (event) => {
                try {
                    const char = event.data;

                    // 创建助手消息容器（仅第一次）
                    if (!assistantMessageDiv) {
                        const messagesDiv = document.getElementById('messages');
                        assistantMessageDiv = document.createElement('div');
                        assistantMessageDiv.className = 'message assistant';

                        contentDiv = document.createElement('div');
                        contentDiv.className = 'message-content content';
                        assistantMessageDiv.appendChild(contentDiv);
                        messagesDiv.appendChild(assistantMessageDiv);
                    }

                    // 累积内容
                    fullContent += char;

                    // 渲染Markdown
                    const html = md.render(fullContent);
                    contentDiv.innerHTML = html;

                    // 高亮代码块
                    contentDiv.querySelectorAll('pre code').forEach(block => {
                        hljs.highlightElement(block);
                    });

                    // 自动滚动到底部
                    const messagesDiv = document.getElementById('messages');
                    messagesDiv.scrollTop = messagesDiv.scrollHeight;

                } catch (e) {
                    console.error('处理消息错误:', e);
                }
            });

            // 监听完成事件
            eventSource.addEventListener('done', () => {
                eventSource.close();
                document.getElementById('userInput').disabled = false;
                document.getElementById('sendBtn').disabled = false;
                document.getElementById('userInput').focus();
                showStatus('✅ 回复完成');
            });

            // 监听错误事件
            eventSource.addEventListener('error', (e) => {
                eventSource.close();
                document.getElementById('userInput').disabled = false;
                document.getElementById('sendBtn').disabled = false;

                if (e.eventPhase === EventSource.CLOSED) {
                    console.log('连接已关闭');
                } else {
                    showStatus('❌ 连接错误！请检查API KEY是否正确配置', true);
                }
            });

            showStatus('⏳ 等待AI回复...');
        }

        function addMessage(content, role) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;

            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);

            // 自动滚动到底部
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
            document.getElementById('userInput').value = '';
            document.getElementById('userInput').focus();
        }

        function showStatus(message, isError = false) {
            const statusEl = document.getElementById('status');
            statusEl.textContent = message;
            statusEl.classList.add('show');
            if (isError) {
                statusEl.classList.add('error');
            } else {
                statusEl.classList.remove('error');
            }
            setTimeout(() => {
                statusEl.classList.remove('show');
            }, 3000);
        }

        // Enter键发送
        document.getElementById('userInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 页面加载完成后聚焦输入框
        window.addEventListener('load', () => {
            document.getElementById('userInput').focus();
        });
    </script>
</body>
</html>
